﻿using System;
using System.Collections.Generic;
using System.Text;
using Common.Logging;
using Utility;

namespace BLL.Action.Core.Caching
{
   public class CacheHelper
    {
       private static ILog logger_ = LogManager.GetLogger(LogDefault.AppInfo);
       public delegate object CacheNotHitAction();

       public static object Cache(ClientCache CachingHolder, string key, CacheNotHitAction action)
       {
           if (CachingHolder != null)
           {
               object cacheObject = CachingHolder.Get(key);
               logger_.Debug("get cache:" + cacheObject);
               if (null != cacheObject)
                {
                    //cache

                    logger_.Debug(string.Format("cache hit:{0},{1}",key,cacheObject));
                    return cacheObject;
                }
                else
                {
                    logger_.Debug(string.Format("renew get:{0}", key));
                    cacheObject = action();
                    if(!CachingHolder.Set(key, cacheObject))
                        logger_.Debug("set cache faile");
                    return cacheObject;
                }
           }
           else
           {
               logger_.Debug("new cache ");
               return action();
           }
       }
       public static object GetCache(ClientCache CachingHolder, string key)
       {
           if (CachingHolder != null)
           {
               object cacheObject = CachingHolder.Get(key);
               logger_.Debug("get cache :"+key);
               return cacheObject;
           }
           else
           {
               logger_.Debug("new cache ");
               return null;
           }
       }
       public static void RemoveCache(ClientCache CachingHolder, string key)
       {
           if (CachingHolder != null)
           {
               bool b = CachingHolder.Delete(key);
               logger_.Debug(string.Format("remove key:{0},{1}",key, b));
           }
           
       }
       
    }
}
